package net.youdi.gateway.handler.response;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.HexUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import net.youdi.gateway.context.KeyStore;
import net.youdi.gateway.properties.GatewayProperties;
import net.youdi.gateway.util.GateWayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @author: scl
 * @date: 2020-07-23 14:00
 * @description 对响应数据进行加密
 */
@Component
public class EncryptResponseHandler implements ResponseDataHandler {

    @Override
    public Object handler(ServerWebExchange exchange, String data, Map container) {
        String userAgent = exchange.getRequest().getHeaders().getFirst("user-agent");
        String bodyHandle = exchange.getRequest().getHeaders().getFirst("bodyHandle");
        if (userAgent != null && bodyHandle!=null){
            if (GateWayUtil.isWeb(userAgent)){
                return encryptWeb(data,container);
            }
            if (GateWayUtil.isAndroid(userAgent)){
                return encryptAndroid(data,container);
            }
            if (GateWayUtil.isIos(userAgent)){
                return encryptIos(data,container);
            }
        }
        return data;
    }

    private Object encryptIos(String data, Map container) {
        byte[] encrypt = KeyStore.iosRsa.encrypt(data.getBytes(StandardCharsets.UTF_8), KeyType.PublicKey);
        return Base64.encode(encrypt);
    }


    private Object encryptAndroid(String data, Map container) {
        byte[] encrypt = KeyStore.androidRsa.encrypt(data.getBytes(StandardCharsets.UTF_8), KeyType.PublicKey);
        return HexUtil.encodeHexStr(encrypt);
    }
    private Object encryptWeb(String data, Map container) {
        /*byte[] encrypt = KeyStore.webRsa.encrypt(data.getBytes(StandardCharsets.UTF_8), KeyType.PublicKey);

        return Base64.encode(encrypt);*/
        return data;
    }
}
